package com.cloud.phone.task.whatsapp;

import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityNodeInfo;

import com.cloud.phone.base.BaseApp;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.task.BaseDealTools;
import com.cloud.phone.task.MsgTaskManger;
import com.cloud.phone.task.taskCongfig.FindIdResouresConfig;
import com.cloud.phone.task.taskCongfig.WhatsAppNodeIdConfig;
import com.cloud.phone.tools.CmdTool;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.utils.AppUtils;

import java.util.ArrayList;
import java.util.List;

public class WhatsAppTaskDealTool extends BaseDealTools {
    WhatsAppTask whatsAppTask;
    public WhatsAppTaskDealTool(WhatsAppTask task) {
        super(task);
        this.whatsAppTask=task;
        this.service=task.service;
    }


    public void allowPermission() throws InterruptedException {
        AccessibilityNodeInfo allowBtNode1 = findNodeFirstById(FindIdResouresConfig.allow_permission_button1);
        AccessibilityNodeInfo allowBtNode2 = findNodeFirstById(FindIdResouresConfig.allow_permission_button2);
        if(allowBtNode1!=null){
            clickXy(allowBtNode1);
            whatsAppTask.showLogAndTsPrint("允许权限");
            Thread.sleep(3000);
        }
        if(allowBtNode2!=null){
            clickXy(allowBtNode2);
            whatsAppTask.showLogAndTsPrint("允许权限");
            Thread.sleep(3000);
        }
    }


    public boolean checkIsInChatAc(){
        AccessibilityNodeInfo etNode = findNodeFirstPlusById(WhatsAppNodeIdConfig.inputEtInChatAcId);
        AccessibilityNodeInfo sendNode = findNodeFirstPlusById(WhatsAppNodeIdConfig.sendBtInChatAcId);
        if(etNode!=null&&sendNode!=null){
            whatsAppTask.showLogAndTsPrint("在聊天详情页面");
            return true;
        }
        whatsAppTask.showLogAndTsPrint("不在聊天详情页面");
        return false;
    }




    /**
     * 根据昵称进入对应的聊天页面，返回是否成功进入
     * @param nickName
     * @return
     * @throws InterruptedException
     */
    public boolean enterInChatDetailsActivity(String nickName) throws InterruptedException {
        boolean isEnterInSuccess=false;
        List<AccessibilityNodeInfo> chatList = findNodesPlusById(WhatsAppNodeIdConfig.chatListItem);
        for(AccessibilityNodeInfo chatItem:chatList){
            List<AccessibilityNodeInfo> singleChatNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.singleChatHeadId);
            if(!isNodeExist(singleChatNode)){
                continue;
            }
            List<AccessibilityNodeInfo> nameNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.contactNameInChatListNode);
            if(isNodeExist(nameNode)){
                String nickNameInList=nameNode.get(0).getText().toString();
                if(nickName.equals(nickNameInList)){
                    clickXy(nameNode.get(0));
                    Thread.sleep(2000);
                    return true;
                }
            }
        }
        return isEnterInSuccess;
    }


    /**
     * 获取当前一屏的对话消息列表数据
     * @return
     * @throws InterruptedException
     */
    public List<ConversationItemBean> getConversationListInfo(int needGetMaxSize) throws InterruptedException {
        List<ConversationItemBean> conversationItemBeans = new ArrayList<>();
        boolean isNotLastIndex = true;
        String lastId="";
        while (conversationItemBeans.size() < needGetMaxSize && isNotLastIndex) {
            List<AccessibilityNodeInfo> chatList = findNodesPlusById(WhatsAppNodeIdConfig.chatListItem);
            for (AccessibilityNodeInfo chatItem : chatList) {
                List<AccessibilityNodeInfo> singleChatNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.singleChatHeadId);
                if (!isNodeExist(singleChatNode)) {
                    continue;
                }

                ConversationItemBean conversationItemBean = new ConversationItemBean();

                List<AccessibilityNodeInfo> nameNodes = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.contactNameInChatListNode);
                List<AccessibilityNodeInfo> msgNodes = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.conversationMsgNode);
                List<AccessibilityNodeInfo> conversationsRowDateNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.conversationsRowDateNode);
                List<AccessibilityNodeInfo> conversationsUnReadCountNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.conversationsUnReadCountNode);
                if (isNodeExist(nameNodes) && isNodeExist(msgNodes) && isNodeExist(conversationsRowDateNode)) {
                    String nickNameInList = nameNodes.get(0).getText().toString();
                    String msgInList = msgNodes.get(0).getText().toString();
                    String dateInList = conversationsRowDateNode.get(0).getText().toString();
                    int unReadCount = 0;
                    if (isNodeExist(conversationsUnReadCountNode)) {
                        String textUnReadText = conversationsUnReadCountNode.get(0).getText().toString();
                        if (MyUtils.isEmpty(textUnReadText)) {
                            textUnReadText = "0";
                        }
                        unReadCount = Integer.parseInt(textUnReadText);
                    }
                    conversationItemBean = new ConversationItemBean();
                    conversationItemBean.setNickName(nickNameInList);
                    conversationItemBean.setMessage(msgInList);
                    conversationItemBean.setUpdateDate(dateInList);
                    conversationItemBean.setUnReadCount(unReadCount);
                    String currentId = String.valueOf(conversationItemBean.hashCode());
                    if(currentId.equals(lastId)){
                        continue;
                    }
                    conversationItemBeans.add(conversationItemBean);
                }
            }

            if(!MyUtils.isEmpty(conversationItemBeans)) {
                lastId = String.valueOf(conversationItemBeans.get(conversationItemBeans.size() - 1).hashCode());
            }
        }
        return conversationItemBeans;
    }


    /**
     * 判断是否切换到对话页面
     * @return
     * @throws InterruptedException
     */
    public boolean isChangeConversationAcMain(boolean needChangeToAc) throws InterruptedException {
        List<AccessibilityNodeInfo> topTabs1 = findNodesPlusById(WhatsAppNodeIdConfig.tabOnBottomMain1);
        List<AccessibilityNodeInfo> topTabs2 = findNodesPlusById(WhatsAppNodeIdConfig.tabOnTopMain2);
        if(isNodeExist(topTabs1)||isNodeExist(topTabs2)){
            if(isNodeExist(topTabs1)) {
                if (topTabs1.get(0).isSelected()) {
                    return true;
                } else {
                    if(needChangeToAc) {
                        clickXy(topTabs1.get(0));
                        Thread.sleep(1000);
                        return isChangeConversationAcMain(true);
                    }else{
                        return false;
                    }
                }
            }else{
                if (topTabs2.get(1).isSelected()) {
                    return true;
                } else {
                    if(needChangeToAc) {
                        clickXy(topTabs2.get(1));
                        Thread.sleep(1000);
                        return isChangeConversationAcMain(true);
                    }else{
                        return false;
                    }
                }
            }
        }else{
            List<AccessibilityNodeInfo> acceptNode = findNodesPlusById(WhatsAppNodeIdConfig.accept_private_msgNode);
            if(isNodeExist(acceptNode)){
                MsgTaskManger.showLog("未登录，无法进入whatsApp首页");
                return false;
            }

            List<AccessibilityNodeInfo> selectLanguageNode = findNodesPlusById(WhatsAppNodeIdConfig.choose_language_node);
            if(isNodeExist(selectLanguageNode)){
                MsgTaskManger.showLog("未登录，无法进入whatsApp首页");
                return false;
            }

            List<AccessibilityNodeInfo> registration_fields_node = findNodesPlusById(WhatsAppNodeIdConfig.registration_fields_node);
            if(isNodeExist(registration_fields_node)){
                MsgTaskManger.showLog("未登录，无法进入whatsApp首页");
                return false;
            }
            if(needChangeToAc) {
                if (Constants.whatsAppPackageName.equals(getCurrentPagePackageName())) {
                    MsgTaskManger.showLog("不在whatsApp首页,返回一下");
                    backOnce();
                    Thread.sleep(2000);
                    return isChangeConversationAcMain(true);
                } else {
                    whatsAppTask.showLogAndTsPrint("当前未在whatsApp内部");
                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
                    Thread.sleep(1000);
                    CmdTool.getInstance().killApp(Constants.whatsAppPackageName);
                    Thread.sleep(1000);
                    whatsAppTask.showLogAndTsPrint("关闭WhatsApp进程重新进入");
                    AppUtils.Companion.launchApp(BaseApp.app, Constants.whatsAppPackageName);
                    Thread.sleep(2000);
                    return isChangeConversationAcMain(true);
                }
            }else{
                return false;
            }
        }
    }



    public WhatsAppUserInfo getUserInfo() throws InterruptedException {
        WhatsAppUserInfo whatsAppUserInfo=null;
        List<AccessibilityNodeInfo> topMenuIds = findNodesPlusById(WhatsAppNodeIdConfig.topRightMenuNodeId);
        if(isNodeExist(topMenuIds)){
            clickXy(topMenuIds.get(0));
            Thread.sleep(2000);
            List<AccessibilityNodeInfo> menuItems = findNodesPlusById(WhatsAppNodeIdConfig.menuItemNodeId);
            if(isNodeExist(menuItems)){
                clickXy(menuItems.get(menuItems.size()-1));
                Thread.sleep(2000);
                List<AccessibilityNodeInfo> profileNodes = findNodesPlusById(WhatsAppNodeIdConfig.profileInfoNodeId);
                if(isNodeExist(profileNodes)){
                    clickXy(profileNodes.get(0));
                    Thread.sleep(2000);
                    List<AccessibilityNodeInfo> detailsInfoList = findNodesPlusById(WhatsAppNodeIdConfig.profile_settings_row_subtext_node);
                    if(isNodeExist(detailsInfoList)){
                        String nickName = "";
                        String statusText = "";
                        String phone = "";
                        nickName = detailsInfoList.get(0).getText().toString();
                        if (detailsInfoList.size() >= 2) {
                            statusText = detailsInfoList.get(1).getText().toString();
                        }
                        if (detailsInfoList.size() >= 3) {
                            phone = detailsInfoList.get(2).getText().toString();
                        }
                        whatsAppUserInfo=new WhatsAppUserInfo();
                        whatsAppUserInfo.setNickName(nickName);
                        whatsAppUserInfo.setStatus(statusText);
                        whatsAppUserInfo.setPhone(phone);
                    }else{
                        MsgTaskManger.showLog("未成功进入个人资料页");
                    }
                }else{
                    MsgTaskManger.showLog("未成功进入设置页面");
                }
            }else{
                MsgTaskManger.showLog("找不到设置按钮");
            }
        }else{
            MsgTaskManger.showLog("找不到菜单按钮");
        }
        return whatsAppUserInfo;
    }


    /**
     * 将用户信息发送给服务端
     * @param userInfo
     */
    private void sendMsgToUpdateUserInfo(WhatsAppUserInfo userInfo) {

    }
}
